package qingke.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import qingke.pojo.Product;

public class Dao {
	public Product add(Product product){
		SessionFactory sf = new Configuration().configure().buildSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		try {
			session.save(product);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		return product;
	}
	
	public List<Product> getAllProduct(){
		SessionFactory sf = new Configuration().configure().buildSessionFactory();
		Session session = sf.openSession();
		Query<Product> query = session.createQuery("from Product", Product.class);
		List<Product> products = query.getResultList();
		if(products!=null){
			return products;
		}
		return null;
	}
	public Product getOneProduct(int id){
		SessionFactory sf = new Configuration().configure().buildSessionFactory();
		Session session = sf.openSession();
		Product product = session.get(Product.class,id);
		return product;
	}
}
